package cn.leizp.springboot.server.netmanger.controller;

import cn.leizp.springboot.server.netmanger.common.inter.IMangerFunc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class StrController {
    private IMangerFunc dynamicService;
    private final ApplicationContext applicationContext;
    private String currentBeanName;

    // 构造函数注入 ApplicationContext 和读取配置项
    @Autowired
    public StrController(ApplicationContext applicationContext, @Value("${ServerImpl.impl-name}") String beanName) {
        this.applicationContext = applicationContext;
        this.currentBeanName = beanName;
        this.dynamicService = applicationContext.getBean(currentBeanName, IMangerFunc.class);
    }

    // 提供接口用于手动变更实现类
    @CrossOrigin
    @GetMapping("/change")
    public String changeImpl(@RequestParam String beanName) {
        try {
            this.dynamicService = applicationContext.getBean(beanName, IMangerFunc.class);
            this.currentBeanName = beanName;
            return "Successfully changed to " + beanName;
        } catch (Exception e) {
            return "Failed to change implementation: " + e.getMessage();
        }
    }

    @CrossOrigin
    @GetMapping("/test")
    public String test() {
        return dynamicService.getConfig();
    }
}
